import CryptoJS from "crypto-js";
import {
	Signature
} from "@/utils/_util";
import {CodeMsg} from "@/utils/errorCode";
const {
	BaseURL,
	BaseURLRDS,
	BaseURLRDSProd,
	BaseURLCAPSXM
} = require('@/utils/api/baseUrl.js')
const {
	xm_uuid,
	xm_appKey,
	xm_appMiYao,
	xm_movedCard
} = require('@/app.config.js');
const signature = new Signature();

/**----------------------AES Util 开始-------------------------------*/
// 获取签名
function getSignature(uniqueCode) {
	const encryptStr =xm_uuid + xm_appKey + xm_appMiYao + uniqueCode;
	// const encoder = new TextEncoder();
	// const encryptByte = encoder.encode(encryptStr);
	const encryptByte =decodeURI(encodeURIComponent(encryptStr)).split("").map(val => val.charCodeAt());

	const changeByte = change(encryptStr, xm_movedCard);
	const mergeByte = mergeByte1(encryptByte, changeByte);
	return CryptoJS.MD5(String.fromCharCode(...mergeByte)).toString(CryptoJS.enc.Hex);
}

function change(encryptStr, moveCard) {
	const encryptByte = Array.from(encryptStr, c => c.charCodeAt(0));
	const encryptLength = encryptByte.length;
	let temp;
	for (let i = 0; i < encryptLength; i++) {
		temp = ((i % moveCard) > ((encryptLength - i) % moveCard)) ? encryptByte[i] : encryptByte[encryptLength - (
			i + 1)];
		encryptByte[i] = encryptByte[encryptLength - (i + 1)];
		encryptByte[encryptLength - (i + 1)] = temp;
	}
	return encryptByte;
}

function mergeByte1(encryptByte, changeByte) {
	let encryptLength = encryptByte.length;
	let encryptLength2 = encryptLength * 2;
	let temp = new Uint8Array(encryptLength2);
	for (let i = 0; i < encryptByte.length; i++) {
		temp[i] = encryptByte[i];
		temp[encryptLength2 - 1 - i] = changeByte[i];
	}
	return temp;
}

function getTimMillis() {
	let counter = 1;
	++counter;
	var counter_str;
	if (counter < 10) {
		counter_str = '00000' + counter;
	} else if (counter < 100) {
		counter_str = '0000' + counter;
	} else if (counter < 1000) {
		counter_str = '000' + counter;
	} else if (counter < 10000) {
		counter_str = '00' + counter;
	} else if (counter < 100000) {
		counter_str = '0' + counter;
	} else if (counter < 1000000) {
		counter_str = counter;
	} else {
		counter = 1;
		counter_str = '00000' + counter;
	}
	return counter_str + new Date().getTime().toString();
};

// 判断是否AES加密
const isAES = (options, code) => {
	const {
		type,
		params
	} = options;
	console.log(params, '1232参数')
	switch (type) {
		case 1:
			return {
				'request': params
			} //普通post请求
			case 2:
				return params || {} //普通get请求
			default:
				return encryptAES(params, code) //post请求 AES加密
	}
}

function keyFilter(key) {
	const length = key.length;
	if (length > 16) {
		key = key.substring(0, 16);
	} else {
		for (let i = 0; i < 16 - length; i++) {
			key += i;
		}
	}
	console.log(key, 'key')
	return key;
}
// 获取AesKey
function getAesKey(timeMillis, appSecret) {
	const key = [];
	const timeLength = timeMillis.length;
	if (timeLength / 2 > 0) {
		key.push(timeMillis.substring(timeLength / 2));
	}

	key.push(appSecret);
	return keyFilter(key.join(''));
}
// 获取时间戳
function generateUniqueCode() {
	let count = uni.getStorageSync('count')
	count = count ? count : "1";
	uni.setStorageSync("count", (Number(count) + 1).toString());
	console.log('generateUniqueCode', count.padStart(6, '0') + new Date().getTime());
	return count.padStart(6, '0') + new Date().getTime();
}

// AES加密方式
function encryptAES(params, code) {
	let uuid = "xmeye";
	let appKey = "ce7e86bf18ffe17bd444dee11727ace7";
	let appSecret = "4a3d05d0f891426ba5ea5135322793ec";
	let movedCard = 8;
	let aesKey = getAesKey(code, appSecret);
	uni.setStorageSync('aesKey', aesKey)
	console.log('aesKey=====', aesKey);

	var keyHex = CryptoJS.enc.Utf8.parse(aesKey);
	// var iv = key // 加密向量和加密key是一样的
	var jsonData = JSON.stringify(params);
	//下面的data参数要求是一个字符串，第一次用的时候我直接传递的是一个对象，出现了错误，要转换成字符串
	var data = CryptoJS.enc.Utf8.parse(jsonData);
	var encrypted = CryptoJS.AES.encrypt(
		data,
		keyHex, {
			mode: CryptoJS.mode.ECB,
			padding: CryptoJS.pad.Pkcs7
		});
	console.log(encrypted.ciphertext.toString().toUpperCase(), '加密的参数params')
	return encrypted.ciphertext.toString().toUpperCase();
}
// AES解密
function decrypt(data, key) {
	// console.log("data before decrypt:\n", data, key);
	const keyHex = CryptoJS.enc.Utf8.parse(key);
	const decryptedData = CryptoJS.AES.decrypt({
		ciphertext: CryptoJS.enc.Hex.parse(data)
	}, keyHex, {
		mode: CryptoJS.mode.ECB,
		padding: CryptoJS.pad.Pkcs7
	}).toString(CryptoJS.enc.Utf8);
	return JSON.parse(decryptedData);
}
/**----------------------AES Util 结束-------------------------------*/

// 封装请求
const requestV3 = (options) => {
	let uuid = xm_uuid
	let appKey = xm_appKey
	let appSecret = xm_appMiYao
	let movedCard = xm_movedCard
	let tms = signature.tms;
	let sig = signature.get(uuid, appKey, appSecret, movedCard);
	let header = {
		uuid: uuid,
		appKey: appKey,
		Authorization: uni.getStorageSync('accessToken'),
		'Content-type': 'application/json; charset=UTF-8',
		'Accept-Language': 'zh_CN'
	};
	let uniCode = generateUniqueCode()
	console.log(uniCode, 'uniCode')
	return new Promise((resolve, reject) => {
		// sig = 'a1cef0b1b33de175c3741617628a0d8c'
		uni.request({
			url: options.url + `/${uniCode}/${getSignature(uniCode)}`,
			header,
			method: options.methods || "POST",
			data: isAES(options, uniCode),
			sslVerify: false,
			timeout: 60000,
			success: (res) => {
				console.log(res, '请求得到的响应数据')
				if(!res.data.code) {  // 请求成功
					let aesKey = uni.getStorageSync('aesKey')
					try {
						// 解密之后的数据
						const data = decrypt(res.data, aesKey)
						console.log('解密之后的数据 --------------- ', data)
						setTimeout(() => {
							return resolve(data.data)
						}, 500)
					} catch (err) {
						return reject(err)
					}
				} else {
					return reject(res)
				}
			},
			fail: (err) => {
				reject(err)
			}
		})
	})
}


/**---------------------------请求开始-------------------------------*/
export const queryMsgList = (params) => {
	const options = {
		url: `${BaseURL}/v3/sysLog/notifyLog/list`,
		method: "POST",
		params,
		type: 3
	}
	// console.log(isAES(params), '加密的参数')
	console.log(options, '传递的接口参数', params)
	return requestV3(options)
}

/**---------------------------请求结束-------------------------------*/

